package com.xhs.service.impl;

import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.xhs.dto.request.TableParams;
import com.xhs.dto.response.TableResult;
import com.xhs.entity.CreateTableEntity;
import com.xhs.mapper.CreateTableMapper;
import com.xhs.message.Result;
import com.xhs.message.ReturnResult;
import com.xhs.service.CreateTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

import static com.xhs.entity.table.CreateTableDetailEntityTableDef.CREATE_TABLE_DETAIL_ENTITY;
import static com.xhs.entity.table.CreateTableEntityTableDef.CREATE_TABLE_ENTITY;

/**
 * @desc:
 * @projectName: spring-boot-demo
 * @author: xhs
 * @date: 2023-10-11 011 20:32
 * @version: JDK 1.8
 */
@Slf4j
@Service
public class CreateTableServiceImpl extends ServiceImpl<CreateTableMapper, CreateTableEntity> implements CreateTableService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 创建表结构
     *
     * @param tableParams 入参
     * @return ReturnResult<Object>
     */
    @Override
    public ReturnResult<Object> createTable(TableParams tableParams) {
        log.info("<-----创建表结构入参:{}----->", tableParams);
        // 1.查询需要创建的表
        List<TableResult> tableResults = queryChain()
                .select(CREATE_TABLE_ENTITY.DB_TYPE, CREATE_TABLE_ENTITY.CHINESE_TABLE_NAME, CREATE_TABLE_ENTITY.SOURCE_TABLE_NAME, CREATE_TABLE_ENTITY.TARGET_TABLE_NAME, CREATE_TABLE_ENTITY.SYSTEM_CODE,
                        CREATE_TABLE_DETAIL_ENTITY.SOURCE_FIELD, CREATE_TABLE_DETAIL_ENTITY.TARGET_FIELD, CREATE_TABLE_DETAIL_ENTITY.FILED_TYPE, CREATE_TABLE_DETAIL_ENTITY.FILED_REMARKS)
                .from(CREATE_TABLE_ENTITY.as("a")).leftJoin(CREATE_TABLE_DETAIL_ENTITY).as("b")
                .on(CREATE_TABLE_ENTITY.ID.eq(CREATE_TABLE_DETAIL_ENTITY.CREATE_TABLE_ID))
                .where(CREATE_TABLE_ENTITY.SYSTEM_CODE.eq(tableParams.getSystemCode()))
                .and(CREATE_TABLE_ENTITY.SOURCE_TABLE_NAME.eq(tableParams.getTableName()))
                .listAs(TableResult.class);
        log.info("<-----查询创建表结构返回值:{}----->", tableResults);
        if (CollectionUtils.isEmpty(tableResults)) {
            return ReturnResult.build(Result.DATA_NOT_EXISTENT).setData(tableParams);
        }
        // 2.构建sql
        String sql = initSql(tableResults);
        log.info("<-----创建表结构的sql语句:{}----->", sql);
        jdbcTemplate.execute(sql);
        return ReturnResult.build(Result.CREATE_TABLE_SUCCESS).setData(sql);
    }

    /**
     * 构建sql
     *
     * @param list 入参
     * @return String
     */
    private String initSql(List<TableResult> list) {
        StringBuffer sql = new StringBuffer();
        String tableName = "";
        String chineseTableName = "";
        for (TableResult result : list) {
            tableName = result.getTargetTableName();
            chineseTableName = result.getChineseTableName();
            break;
        }
        if (StringUtils.hasLength(tableName)) {
            sql.append("CREATE TABLE ").append(tableName).append("(");
            for (TableResult tableResult : list) {
                sql.append("`").append(tableResult.getTargetField()).append("` ")
                        .append(tableResult.getFiledType()).append(" COMMENT '").append(tableResult.getFiledRemarks())
                        .append("' ,");
            }
            sql.append(") ENGINE = InnoDB AUTO_INCREMENT = 0 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT =  '")
                    .append(chineseTableName)
                    .append("' ROW_FORMAT = DYNAMIC;");
        }
        return sql.toString().replace(",)",")");
    }
}
